# coding=utf-8
import random
from urllib import urlencode, quote
import misaka as m

import requests

from db.model import Article
from db.user import User
from libs.Tools import WashTools
from view.MarkdownRender import BleepRenderer


class ArticleParser:
    @classmethod
    def getPageContent(cls, qiniu_url, path, title='', refresh=True):
        User.db.connect()
        art_list = Article.select().where(Article.path == path)
        etag = ""
        article = None
        if len(art_list) > 0:
            article = art_list[0]
            etag = article.etag
        if refresh:
            req_url = qiniu_url + path.replace('/', '%2f') + '?v=' + str(random.random())
            req = requests.get(url=req_url, headers={"If-None-Match": etag})
            req.encoding = 'utf8'

        if not refresh or req.status_code == 304:
            if article is None:
                return 404, u"404 not found", {}, article
            if refresh:
                content = article.content
            else:
                content = article.html

            info = {
                'id': article.id,
                'date': article.date,
                'title': article.title,
                'descripition': article.descripition,
                'tags': article.tags,
                'comments': article.comments,
            }
            article.read_count += 1
            article.save()
        elif req.status_code == 200:
            content = req.text
            info, content = cls.splitHeadInfo(content)
            info = WashTools.washHeader2Field(info, path, title)
            data = {
                'etag': req.headers['etag'],
                'path': path
            }
            data.update(info)
            data['content'] = content

            # 说明数据库中没有这个文章，则找找这个id
            if article is None:
                art_list = Article.select().where(Article.id == info['id'])
                if len(art_list) > 0:
                    article = art_list[0]
                else:
                    article = Article.create(**data)

            # 不能用article.update 好烦啊！！
            article.date = data['date']
            article.path = data['path']
            article.comments = data['comments']
            article.etag = data['etag']
            article.content = data['content']
            article.descripition = data['descripition']
            article.tags = data['tags']

            article.read_count += 1
            if article.title == '':
                article.title = title
                info['title'] = title

            article.save()
        else:
            if article is not None:
                article.delete_instance()
            return 404, "", {}, article
        info['read_count'] = article.read_count
        info['font_count'] = len(article.content)
        User.db.close()
        return 200, content, info, article

    @classmethod
    def getPageHTML(cls, qiniu_url, path, base_url, title='', refresh=True):
        code, content, info, article = cls.getPageContent(qiniu_url, path, title=title, refresh=refresh)
        if code == 200:
            if refresh:
                renderer = BleepRenderer(qiniu_url, base_url)
                md = m.Markdown(renderer,
                                extensions=(
                                    'fenced-code', 'footnotes', 'strikethrough', 'tables', 'autolink', 'underline',))

                html = md(content)
                html = '%s' % html

                article.html = html
                article.save()
            else:
                html = article.html
            return code, info, html
        else:
            return code, {}, u'404 not found'

    @classmethod
    def splitHeadInfo(cls, content):
        d = {}
        split_index = 0
        lines = content.split('\n')
        for i, line in enumerate(lines):
            if line.strip() == "":
                pass
            elif ":" not in line:
                if line.strip().startswith('---'):
                    split_index = i + 1
                else:
                    split_index = i
                break
            else:
                key = line.split(":", 1)[0].strip()
                value = line.split(":", 1)[1].strip()
                d.update(dict({key: value}))
        text = '\n'.join(lines[split_index:])
        return d, text

        # def washInfo(self, info, list=None):
        #     if list is None:
        #         list = ['id', 'date', 'title', 'descripition', 'tags', 'comments']
        #     d = {}
        #     for li in list:
        #         if li in info:
        #             if li == 'date':
        #                 d[li] = datetime.datetime.strptime(info[li], '%Y/%m/%d %H:%M:%S')
        #             else:
        #                 d[li] = info[li]
        #         elif li != 'id':
        #             d[li] = ''
        #         else:
        #             d['id'] = str(hashlib.md5(str(random.random())).hexdigest())
        #     return d
